<?php

namespace App\Admin\Repositories;

use App\Models\RoomUser;
use App\Models\User as Model;
use Dcat\Admin\Repositories\EloquentRepository;
use Dcat\Admin\Form;
use App\Models\Room;
use Dcat\Admin\Show;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

class User extends EloquentRepository
{

    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    protected string $roomClass = Room::class;

    protected string $roomUser = RoomUser::class;
    // 返回你的id字段名称，默认“id”
    protected $keyName = '_id';

    // 查询编辑页数据
    // 这个方法需要返回一个数组
    public function edit(Form $form)
    {
        // 获取id
        $id = $form->builder()->getResourceId();
        $find = $this->eloquentClass::find($id)->toArray();
        if ( !$find ) return [];
        // 获取用户房间
        $userRoom = $this->roomUser::where('user_id', $id)->select('room_id')->get()->toArray();
        if ( !$userRoom ) return [];
        $find['room_ids'] = array_column($userRoom, 'room_id');
        $find['room_list'] = $this->roomClass::select('id', 'name')->get()->toArray();
        return $find;
    }


    /**
     * 更新数据.
     * @param Form $form
     * @return bool|null
     */
    public function update(Form $form)
    {

        /* @var EloquentModel $builder */
        $model = $this->model();

        if ( !$model->getKey() ) {
            $model->exists = true;

            $model->setAttribute($model->getKeyName(), $form->getKey());
        }

        $result = null;

        DB::transaction(function () use ($form, $model, &$result) {
            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ( $relations ) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }
            $room_ids = $updates['room_ids'] ?? [];

            // 1 [1,2]  del 2
            // 2 [1,2]  del 2
            //1,3 [1,2]   add 3
            if ( $room_ids ) {
                $id = (int)$form->builder()->getResourceId();
                $this->saveRoomUser($form, $room_ids, $id);

            }

            unset($updates['room_ids']);
            foreach ($updates as $column => $value) {

                /* @var EloquentModel $model */
                $model->setAttribute($column, $value);
            }

            $result = $model->update();
            $this->updateRelation($form, $model, $relations, $relationKeyMap);

        });

        return $result;
    }


    /**
     * 新增记录.
     *
     * @param Form $form
     * @return mixed
     */
    public function store(Form $form)
    {
        $result = null;

        DB::transaction(function () use ($form, &$result) {
            $model = $this->model();

            $updates = $form->updates();

            [$relations, $relationKeyMap] = $this->getRelationInputs($model, $updates);

            if ( $relations ) {
                $updates = Arr::except($updates, array_keys($relationKeyMap));
            }
            $room_ids = $updates['room_ids'];
            unset($updates['room_ids']);
            foreach ($updates as $column => $value) {

                $model->setAttribute($column, $value);
            }

            $result = $model->save();
            $this->updateRelation($form, $model, $relations, $relationKeyMap);

            if ( $result && $room_ids ) {

                $this->saveRoomUser($form, $room_ids, $this->model()->getKey());
            }

        });


        return $this->model()->getKey();
    }

    /**
     * @param Form $form
     * @param mixed $room_ids
     * @param $id
     * @return void
     */
    function saveRoomUser(Form $form, mixed $room_ids, $id): void
    {

        $roomUserModel = $this->roomUser;
        $roomUserList = $roomUserModel::where('user_id', $id)->select('room_id', 'user_id')->get()->toArray();
        if ( $roomUserList ) {
            $roomUserRoomIds = array_column($roomUserList, 'room_id');
            $del = [];
            foreach ($room_ids as $key => $val) {
                if ( in_array($val, $roomUserRoomIds) ) {
                    unset($roomUserRoomIds[$key]);
                    $del = $roomUserRoomIds;
                } else {

                    $roomUserModel::create([
                        'room_id' => (int)$val,
                        'user_id' => $id,
                        'create_time' => time(),
                        'update_time' => time(),
                    ]);

                }
            }
            if ( $del ) {
                $roomUserModel::where('user_id', $id)->whereIn("room_id", $del)->delete();
            }

        } else {
            foreach ($room_ids as $val) {

                $roomUserModel::create([
                    'room_id' => (int)$val,
                    'user_id' => $id,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);

            }

        }
    }


  public function detail(Show $show)
  {
      // 获取数据主键值
      $id = $show->getId();
      return $id;


  }


}
